/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cinescope2014.boundaries;

import cinescope2014.utilities.Globale;
import java.awt.Rectangle;
import java.sql.*;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author pascal
 */
public class JIFGenerique extends javax.swing.JInternalFrame {

    private Connection icn;
    private String isTable;
    private DefaultTableModel idtm;
    private int iiColonnes;

    /**
     * Creates new form JIFGenerique
     *
     * @param asTable
     */
    public JIFGenerique(String asTable) {
        initComponents();

        icn = Globale.getConnexion();
        isTable = asTable;
        remplirTable(asTable);

        jButtonAjouter.setEnabled(false);
        jButtonAnnulerPlus.setEnabled(false);
//        jButtonModifier.setEnabled(false);
//        jButtonSupprimer.setEnabled(false);

        setTitle("CRUD sur " + asTable + " from generique");

        setVisible(true);
    } /// class Constructeur

    /**
     *
     */
    private void scrollerVersDerniereLigne() {
        int liMax = jTableGenerique.getRowCount() - 1;
        jTableGenerique.getSelectionModel().setSelectionInterval(liMax, liMax);
        jTableGenerique.scrollRectToVisible(new Rectangle(jTableGenerique.getCellRect(liMax, 0, true)));
    } /// scrollerVersDerniereLigne

    /**
     *
     * @param asTable
     */
    private void remplirTable(String asTable) {
        Object[] tEntetes;
        Object[][] tDataTable;
        Object[] tDataLigne;

        String lsSQL;
        PreparedStatement lpst;
        ResultSet lrs;

        try {
            lsSQL = "CALL " + asTable + "selectAll()";
            lpst = icn.prepareStatement(lsSQL, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
            lrs = lpst.executeQuery();

            // --- Recuperation de la structure du curseur
            ResultSetMetaData lrsmd = lrs.getMetaData();

            // --- Nombre de colonnes du curseur
            iiColonnes = lrsmd.getColumnCount();

            // --- Noms des colonnes
            tEntetes = new Object[iiColonnes];
            for (int i = 0; i < iiColonnes; i++) {
                tEntetes[i] = lrsmd.getColumnName(i + 1);
            }

            // --- Pour les donnees de la JTable
            // --- Pour obtenir le nombre de lignes du curseur
            lrs.last();
            int liLignes = lrs.getRow();
            tDataTable = new Object[liLignes][iiColonnes];

            lrs.beforeFirst();
            int i = 0;
            // --- Balayage des lignes
            while (lrs.next()) {
                // --- Balayage des colonnes pour construire une ligne
                tDataLigne = new Object[iiColonnes];
                for (int j = 0; j < iiColonnes; j++) {
                    if (lrs.getObject(j + 1) == null) {
                        tDataLigne[j] = "NUL";
                    } else {
                        tDataLigne[j] = lrs.getObject(j + 1).toString();
                    }
                }
                tDataTable[i] = tDataLigne;
                i++;
            }

            // --- Affectation des tableaux d'objets a la JTable
            idtm = new DefaultTableModel(tDataTable, tEntetes);
            jTableGenerique.setModel(idtm);

            // Fermetures
            lrs.close();
            lpst.close();

        } /// du try
        catch (SQLException e) {
            jLabelMessage.setText(e.getMessage());
        }
    } /// remplirTable

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTableGenerique = new javax.swing.JTable();
        jButtonAjouter = new javax.swing.JButton();
        jButtonSupprimer = new javax.swing.JButton();
        jButtonModifier = new javax.swing.JButton();
        jLabelMessage = new javax.swing.JLabel();
        jButtonPlus = new javax.swing.JButton();
        jButtonAnnulerPlus = new javax.swing.JButton();

        setClosable(true);
        setIconifiable(true);
        setMaximizable(true);
        setResizable(true);

        jTableGenerique.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jScrollPane1.setViewportView(jTableGenerique);

        jButtonAjouter.setText("Ajouter");
        jButtonAjouter.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonAjouterActionPerformed(evt);
            }
        });

        jButtonSupprimer.setText("Supprimer");
        jButtonSupprimer.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonSupprimerActionPerformed(evt);
            }
        });

        jButtonModifier.setText("Modifier");
        jButtonModifier.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonModifierActionPerformed(evt);
            }
        });

        jLabelMessage.setText("Message :     ");

        jButtonPlus.setText("+");
        jButtonPlus.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonPlusActionPerformed(evt);
            }
        });

        jButtonAnnulerPlus.setText("Annuler +");
        jButtonAnnulerPlus.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonAnnulerPlusActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButtonAjouter)
                        .addGap(31, 31, 31)
                        .addComponent(jButtonSupprimer)
                        .addGap(30, 30, 30)
                        .addComponent(jButtonModifier)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButtonAnnulerPlus))
                    .addComponent(jLabelMessage, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 623, Short.MAX_VALUE))
                .addGap(18, 18, 18)
                .addComponent(jButtonPlus)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButtonPlus))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButtonAjouter)
                    .addComponent(jButtonSupprimer)
                    .addComponent(jButtonModifier)
                    .addComponent(jButtonAnnulerPlus))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabelMessage)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButtonModifierActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonModifierActionPerformed
        //
        int liLigneSelectionnee = jTableGenerique.getSelectedRow();

        // Aucune ligne selectionnee
        if (liLigneSelectionnee == -1) {
            jLabelMessage.setText("Sélectionnez une ligne !!!");
        } else {
            // C'est une nouvelle ligne
            if (jTableGenerique.getValueAt(liLigneSelectionnee, 0) == null) {
                idtm.removeRow(liLigneSelectionnee);
            } else {

            }
        }

    }//GEN-LAST:event_jButtonModifierActionPerformed

    private void jButtonSupprimerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonSupprimerActionPerformed
        //
        int liLigneSelectionnee = jTableGenerique.getSelectedRow();

        // Aucune ligne selectionnee
        if (liLigneSelectionnee == -1) {
            jLabelMessage.setText("Sélectionnez une ligne !!!");
        } else {
            // C'est une nouvelle ligne
            if (jTableGenerique.getValueAt(liLigneSelectionnee, 0) == null) {
                idtm.removeRow(liLigneSelectionnee);
            } else {
                String lsSQL;
                lsSQL = "CALL " + isTable + "Delete(?)";
                try {
                    PreparedStatement lpst = icn.prepareStatement(lsSQL);
                    lpst.setString(1, jTableGenerique.getValueAt(liLigneSelectionnee, 0).toString());
                    lpst.executeUpdate();
                    icn.commit();
                    idtm.removeRow(liLigneSelectionnee);
                } catch (SQLException e) {
                    jLabelMessage.setText(e.getMessage());
                }
            }
        }
    }//GEN-LAST:event_jButtonSupprimerActionPerformed

    private void jButtonAjouterActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAjouterActionPerformed
        //
        int liLigne;

        liLigne = jTableGenerique.getSelectedRow();

        if (liLigne == -1) {
            jLabelMessage.setText("Sélectionnez une ligne !!!");
        } else {
            StringBuilder lsbSQL = new StringBuilder();
            lsbSQL.append("CALL ");
            lsbSQL.append(isTable);
            lsbSQL.append("Insert(");
            for (int i = 0; i < iiColonnes; i++) {
                lsbSQL.append("?,");
            }
            lsbSQL.deleteCharAt(lsbSQL.length() - 1);
            lsbSQL.append(")");
            System.out.println(lsbSQL);
            try {
                PreparedStatement lpst = icn.prepareStatement(lsbSQL.toString());

                lpst.setInt(1, Types.NULL);

                for (int i = 0; i < iiColonnes - 1; i++) {
                    lpst.setString(i + 2, jTableGenerique.getValueAt(liLigne, i + 1).toString());
                }

                lpst.executeUpdate();
                icn.commit();
                jButtonAjouter.setEnabled(false);
                jButtonAnnulerPlus.setEnabled(false);
                jButtonPlus.setEnabled(true);
            } catch (SQLException e) {
                jLabelMessage.setText(e.getMessage());
            }
        }

    }//GEN-LAST:event_jButtonAjouterActionPerformed

    private void jButtonPlusActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonPlusActionPerformed
        //
        String[] tLigne = new String[iiColonnes];
        idtm.addRow(tLigne);
        jButtonAjouter.setEnabled(true);
        jButtonPlus.setEnabled(false);
        jButtonAnnulerPlus.setEnabled(true);
        scrollerVersDerniereLigne();
    }//GEN-LAST:event_jButtonPlusActionPerformed

    private void jButtonAnnulerPlusActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAnnulerPlusActionPerformed
        // 
        idtm.removeRow(idtm.getRowCount() - 1);
        jButtonAjouter.setEnabled(false);
        jButtonPlus.setEnabled(true);
        jButtonAnnulerPlus.setEnabled(false);
    }//GEN-LAST:event_jButtonAnnulerPlusActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonAjouter;
    private javax.swing.JButton jButtonAnnulerPlus;
    private javax.swing.JButton jButtonModifier;
    private javax.swing.JButton jButtonPlus;
    private javax.swing.JButton jButtonSupprimer;
    private javax.swing.JLabel jLabelMessage;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTableGenerique;
    // End of variables declaration//GEN-END:variables
}
